package com.lhb.aicodemother.ai.core.handler;

import cn.hutool.core.util.StrUtil;
import com.lhb.aicodemother.model.entity.User;
import com.lhb.aicodemother.model.enums.ChatHistoryMessageTypeEnum;
import com.lhb.aicodemother.service.ChatHistoryService;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/*
* 简单文本流处理器
* */
@Slf4j
public class SimpleTextStreamHandler {

    public Flux<String> handle(Flux<String> originFlux, ChatHistoryService chatHistoryService, long appId, User loginUser) {
        StringBuilder aiResponse = new StringBuilder();
        return originFlux
                .map(chunk -> {
                    // 将响应内容拼接
                    aiResponse.append(chunk);
                    return chunk;
                })
                .doOnComplete(() -> {
                    // 响应完成将ai返回内容保存到历史对话
                    String aiResponseString = aiResponse.toString();
                    if (StrUtil.isNotBlank(aiResponseString)) {
                        chatHistoryService.addChatMessage(appId, aiResponseString, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                    }
                })
                .doOnError(error -> {
                    // 响应失败，将失败原因保存到历史对话
                    String aiError = "Ai回复失败：" + error.getMessage();
                    chatHistoryService.addChatMessage(appId, aiError, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                });
    }
}
